package org.jjche.file.modules.file.service;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.SneakyThrows;
import org.dromara.x.file.storage.core.upload.FilePartInfo;
import org.jjche.file.modules.file.domain.FilePartDetailDO;
import org.jjche.file.modules.file.mapper.FilePartDetailMapper;
import org.springframework.stereotype.Service;

/**
 * 用来将文件分片上传记录保存到数据库，这里使用了 MyBatis-Plus 和 Hutool 工具类
 * 目前仅手动分片分片上传时使用
 */
@Service
public class FilePartDetailService extends ServiceImpl<FilePartDetailMapper, FilePartDetailDO> {

    /**
     * 保存文件分片信息
     *
     * @param info 文件分片信息
     */
    @SneakyThrows
    public void saveFilePart(FilePartInfo info) {
        FilePartDetailDO detail = toFilePartDetail(info);
        if (save(detail)) {
            info.setId(String.valueOf(detail.getId()));
        }
    }

    /**
     * 删除文件分片信息
     */
    public void deleteFilePartByUploadId(String uploadId) {
        remove(new LambdaQueryWrapper<FilePartDetailDO>().eq(FilePartDetailDO::getUploadId, uploadId));
    }

    /**
     * 将 FilePartInfo 转成 FilePartDetail
     *
     * @param info 文件分片信息
     */
    public FilePartDetailDO toFilePartDetail(FilePartInfo info) throws JsonProcessingException {
        FilePartDetailDO detail = new FilePartDetailDO();
        detail.setPlatform(info.getPlatform());
        detail.setUploadId(info.getUploadId());
        detail.setETag(info.getETag());
        detail.setPartNumber(info.getPartNumber());
        detail.setPartSize(info.getPartSize());
        detail.setHashInfo(JSONUtil.toJsonStr(info.getHashInfo()));
        return detail;
    }
}
